package top.lyc829.zzl_android.ui.team.my_team.activity;

import androidx.lifecycle.ViewModelProvider;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Response;
import top.lyc829.zzl_android.MyApp;
import top.lyc829.zzl_android.R;
import top.lyc829.zzl_android.databinding.ActivityFragmentBinding;
import top.lyc829.zzl_android.logic.bean.ActivityBean;
import top.lyc829.zzl_android.logic.bean.BaseDetailBean;
import top.lyc829.zzl_android.logic.bean.ResultBean;
import top.lyc829.zzl_android.logic.network.Network;
import top.lyc829.zzl_android.logic.util.HttpUtil;
import top.lyc829.zzl_android.logic.util.Url;
import top.lyc829.zzl_android.logic.util.Utils;
import top.lyc829.zzl_android.logic.util.gson.JsonUtilNew;
import top.lyc829.zzl_android.ui.base_detail.BaseDetailActivity;
import top.lyc829.zzl_android.ui.main.LazyFragment;
import top.lyc829.zzl_android.ui.team.my_team.MyTeamViewModel;
import top.lyc829.zzl_android.ui.thing.dynamic.DynamicRecyclerViewAdapter1;

public class ActivityFragment extends LazyFragment {

    private MyTeamViewModel mViewModel;
    ActivityFragmentBinding binding;
    MyActivityAdapter adapter;

    public static ActivityFragment newInstance() {
        return new ActivityFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
//        return inflater.inflate(R.layout.activity_fragment, container, false);
        binding = ActivityFragmentBinding.inflate(getLayoutInflater());
        return  binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = new ViewModelProvider(requireActivity()).get(MyTeamViewModel.class);

        initRecycler();
    }

    @Override
    public void lazyInit() {
        initData();
        observer();
        clickListener();
    }

    private void clickListener() {
        // 跳转到基地详情页
        adapter.setOnItemClickListener((adapter1, view, position) -> {
            int baseId = adapter.getData().get(position).getBaseId();
            Intent intent = new Intent(getActivity(), BaseDetailActivity.class);
            intent.putExtra("id", baseId);
            startActivity(intent);
        });

        binding.btnFinishTeam.setOnClickListener(v -> {

            if (mViewModel.getActivitiesLivaData().getValue() == null || mViewModel.getTeamId().getValue() == null) {
                return;
            }

            List<String> names = new ArrayList<>();
            mViewModel.getActivitiesLivaData().getValue().forEach(activityBean -> {
                if (activityBean.getIsDelete().equals(0)) {
                    names.add(activityBean.getName());
                }
            });

            new MaterialDialog.Builder(getContext())
                    .title("活动选择")
                    .content("全部活动都结束后将退出团队，无法编辑游记!")
                    .items(names)
                    .itemsCallbackSingleChoice(
                            0,
                            (dialog, itemView, which, text) -> {
                                finishTeam(which);
                                return true;
                            })
                    .positiveText("结束")
                    .negativeText("取消")
                    .show();
        });

    }

    private void finishTeam(int position) {

        List<Integer> activityIds = new ArrayList<>();
        mViewModel.getActivitiesLivaData().getValue().forEach(activityBean -> {
            if (activityBean.getIsDelete().equals(0)) {
                activityIds.add(activityBean.getId());
            }
        });

        Network.finishTeam(Utils.getUserId(),
                mViewModel.getTeamId().getValue(),
                activityIds.get(position),
                new HttpUtil.MyCallback() {
                    @Override
                    public void success(Response res) throws IOException {
                        String resStr = res.body().string();
                        ResultBean<Void> resultBean = JsonUtilNew.fromJsonObject(resStr, Void.class);
                        if (resultBean.getCode().equals(200)) {
                            getActivity().runOnUiThread(() -> {
                                Utils.showToast("操作成功");
                                mViewModel.getActivityInTeam(mViewModel.getTeamId().getValue());
                            });

                        } else {
                            Utils.showToastSync("操作失败");
                            Utils.Sout(resultBean.getMsg());
                        }
                    }

                    @Override
                    public void failed(IOException e) {
                        Utils.Sout(e.getMessage());
                    }
                }
        );
    }


    private void observer() {

        mViewModel.getTeamInfoBeanLiveData().observe(getViewLifecycleOwner(), myTeamInfoBean -> {
            if (myTeamInfoBean.getLeader().getId().equals(Utils.getUserId())) {
                binding.btnFinishTeam.setVisibility(View.VISIBLE);
            } else {
                binding.btnFinishTeam.setVisibility(View.INVISIBLE);
            }
        });

        mViewModel.getActivitiesLivaData().observe(getViewLifecycleOwner(), activityBeans -> {

            int count = 0;
            for (ActivityBean activityBean : activityBeans) {
                if (activityBean.getIsDelete().equals(1)) {
                    count += 1;
                }
            }
            if (activityBeans.size() == count) {
                getActivity().finish();
            }

            adapter.setList(activityBeans);

            for (int i = 0; i < adapter.getData().size(); i++) {
                HashMap<String, String> body = new HashMap<>();
                body.put("id", String.valueOf(adapter.getItem(i).getBaseId()));
                HttpUtil httpUtil = HttpUtil.getInstance(MyApp.getContext());
                int finalI = i;
                httpUtil.get(Url.GET_BASE_DETAIL, body, new HttpUtil.MyCallback() {
                    @Override
                    public void success(Response res) throws IOException {
                        String resultStr = res.body().string();
                        ResultBean<BaseDetailBean> resultBean = JsonUtilNew.fromJsonObject(resultStr, BaseDetailBean.class);
                        if (resultBean.getCode().equals(200)) {
                            getActivity().runOnUiThread(() -> {
                                ActivityBean activity = adapter.getItem(finalI);
                                activity.setBaseName(resultBean.getData().getTitle());
                                adapter.setData(finalI, activity);
                            });

                        } else {
                            failed(new IOException(resultBean.getMsg()));
                        }
                    }

                    @Override
                    public void failed(IOException e) {
                        Utils.SoutErr(e.getMessage());
                    }
                });
            }


        });
    }

    private void initData() {
        //mViewModel.getActivityInTeam(mViewModel.getTeamId().getValue());

    }

    private void initRecycler() {
        adapter = new MyActivityAdapter();
        binding.myTeamActivityRecycler.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.myTeamActivityRecycler.setAdapter(adapter);
        adapter.setList(null);
    }


}